<template>
  <ele-page
    flex-table
    :multi-card="false"
    hide-footer
    style="min-height: 420px"
  >
    <organization-search
      @search="reload"
      :cache-key="getCurrentInstance().type.name"
    />
    <ele-card :body-style="{ paddingTop: '8px' }" flex-table>
      <ele-pro-table
        sticky
        ref="tableRef"
        row-key="organization_id"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        :highlight-current-row="true"
        :export-config="{ fileName: '机构数据' }"
        :default-expand-all="true"
        :pagination="false"
        :cache-key="getCurrentInstance().type.name"
      >
        <template #toolbar>
          <el-button
            type="primary"
            class="ele-btn-icon"
            :icon="PlusOutlined"
            @click="openAdd()"
          >
            新建
          </el-button>
          <el-button
            class="ele-btn-icon"
            :icon="ColumnHeightOutlined"
            @click="expandAll"
          >
            展开全部
          </el-button>
          <el-button
            class="ele-btn-icon"
            :icon="VerticalAlignMiddleOutlined"
            @click="foldAll"
          >
            折叠全部
          </el-button>
        </template>
        <template #action="{ row }">
          <el-link type="primary" underline="never" @click="openAdd(row)">
            添加
          </el-link>
          <el-divider direction="vertical" />
          <el-link type="primary" @click="openEdit(row)"> 修改 </el-link>
          <el-divider direction="vertical" />
          <el-link type="primary" underline="never" @click="openView(row)">
            查看
          </el-link>
          <el-divider direction="vertical" />
          <el-link
            type="danger"
            underline="never"
            @click="action('remove', row)"
          >
            删除
          </el-link>
        </template>
      </ele-pro-table>
    </ele-card>

    <!-- 新增 -->
    <organization-edit
      :organizationId="parent_id"
      :organizationData="organizationData"
      action="add"
      v-model="showAdd"
      @done="reload"
    />

    <!-- 修改 -->
    <organization-edit
      action="edit"
      :organizationId="parent_id"
      :organizationData="organizationData"
      :data="current"
      v-model="showEdit"
      @done="reload"
    />

    <!-- 查看 -->
    <organization-edit
      action="view"
      :organizationId="parent_id"
      :organizationData="organizationData"
      :data="current"
      v-model="showView"
    />
  </ele-page>
</template>

<script setup>
import { computed, ref, getCurrentInstance } from "vue";
import { toTree } from "ele-admin-plus/es";
import {
  PlusOutlined,
  ColumnHeightOutlined,
  VerticalAlignMiddleOutlined,
} from "@/components/icons";

import OrganizationSearch from "./components/organization-search.vue";
import OrganizationEdit from "./components/organization-edit.vue";
import { useDictData } from "@/utils/use-dict-data";
import { useOperator } from "@/hooks/operator";
import { useTable } from "@/hooks/useTable";
import { useModal } from "@/hooks/useModal";
import {
  listOrganizations,
  removeOrganizationBatch,
} from "@/api/system/organization";

const [organizationDicts] = useDictData(["organization_type"]);

// 使用useTable
const { tableRef, datasource, reload, current, expandAll, foldAll } = useTable({
  getPages: listOrganizations,
  afterQuery: (data) => {
    //   organizationData.value = toTree({
    //     data,
    //     idField: "organization_id",
    //     parentIdField: "parent_id",
    //   });
    //   return organizationData.value;
    //   let res = toTree({
    //   data,
    //   idField: "organization_id",
    //   parentIdField: "parent_id",
    // });
    // console.log(res);
    console.log("查询后前处理", data);
    let res = toTree({
      data,
      idField: "organization_id",
      parentIdField: "parent_id",
    });
    organizationData.value = res;
    console.log("查询后处理", data, res);
    return res;
  },
});

// 使用useOperator
const { action } = useOperator({
  actionConfigs: {
    remove: {
      title: "删除",
      api: removeOrganizationBatch,
      confirmText: "确定要删除“{%s}”吗?",
      beforeSubmit: ({ type, rows, formData }) => {
        if (rows[0].children?.length) {
          console.log("删除前子节点", rows);
          return new Error("请先删除子节点");
        }
        return { type, rows, formData };
      },
    },
  },
  idField: "organization_id",
  idName: "organization_name",
  reload,
});

defineOptions({ name: "SystemOrganizationTable" });

/** 表格列配置 */
const columns = computed(() => {
  return [
    {
      type: "index",
      columnKey: "index",
      width: 50,
      align: "center",
      fixed: "left",
    },
    {
      prop: "organization_name",
      label: "机构名称",
      sortable: "custom",
      minWidth: 160,
    },
    {
      columnKey: "organization_type",
      prop: "organization_type",
      label: "机构类型",
      minWidth: 100,
      align: "center",
      sortable: "custom",
      filters: organizationDicts.value.map((d) => {
        return { text: d.dict_data_name, value: d.dict_data_code };
      }),
      formatter: (row) => {
        return organizationDicts.value.find(
          (d) => d.dict_data_code == row.organization_type,
        )?.dict_data_name;
      },
    },
    {
      prop: "sort_number",
      label: "排序号",
      minWidth: 100,
      align: "center",
    },
    {
      prop: "created_at",
      label: "创建时间",
      sortable: "custom",
      width: 180,
      align: "center",
    },
    {
      columnKey: "action",
      label: "操作",
      width: 220,
      align: "center",
      slot: "action",
      hideInPrint: true,
      hideInExport: true,
    },
  ];
});

/** 上级机构id */
const parent_id = ref();

/** 机构下拉数据 */
const organizationData = ref([]);

// 使用hook创建各个弹窗
const { visible: showAdd, open: openAdd } = useModal({
  beforeOpen: (row) => {
    console.log("新增前处理", row);
    parent_id.value = row?.organization_id || 0; // 确保parent_id有默认值
    console.log("新增前处理", parent_id.value);
    current.value = null; // 重置current
  },
});

const { visible: showEdit, open: openEdit } = useModal({
  beforeOpen: async (row) => {
    // 更新useModal中的current值
    current.value = row; // 重置current
  },
});

const { visible: showView, open: openView } = useModal({
  beforeOpen: async (row) => {
    current.value = row; // 设置当前行数据
  },
});
</script>
